import 'dart:convert';
import 'dart:io';
import 'dart:math';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:lwtools/untils/unitl.dart';
import 'package:process_run/shell.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  String _toolPath = '';
  String _symbolsPath = '';
  String _mappingPath = '';
  TextStyle leftStyle = const TextStyle(
    color: Colors.black87,
    fontSize: 16,
  );
  String _platformValue = "Android";
  String _version = '6.2.0';
  String _appid = '101a4430e1';
  String _appkey = '66b3f8de-e52a-4df9-8cf6-485cbada4d23';
  String _bundleid = 'com.ctufeel.audio';
  String _error = '';
  List<String> logs = [];
  bool _uploading = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        padding: const EdgeInsets.symmetric(vertical: 10),
        margin: const EdgeInsets.symmetric(horizontal: 20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            // const SizedBox(
            //   height: 10,
            // ),
            Row(
              children: [
                Text(
                  '平台：',
                  style: leftStyle,
                ),
                DropdownButton(
                  items: const [
                    DropdownMenuItem<String>(
                      child: Text('IOS'),
                      value: "IOS",
                    ),
                    DropdownMenuItem<String>(
                      child: Text('Android'),
                      value: "Android",
                    ),
                  ],
                  onChanged: <String>(value) {
                    setState(() {
                      _platformValue = value;
                      if (_platformValue == "IOS") {
                        _appid = '101a4430e1';
                        _appkey = '66b3f8de-e52a-4df9-8cf6-485cbada4d23';
                      } else {
                        _appid = '16f59a0977';
                        _appkey = '21ffbf52-d3bb-460c-89b7-406697c6700f';
                      }
                    });
                  },
                  icon: const Icon(Icons.arrow_drop_down),
                  value: _platformValue,
                  focusColor: Colors.transparent,
                  // dropdownColor: Colors.transparent,
                )
              ],
            ),
            Container(
              padding: const EdgeInsets.symmetric(vertical: 10),
              child: Row(
                children: [
                  Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(
                        'AppId:',
                        style: leftStyle,
                      ),
                      Container(
                        margin: const EdgeInsets.only(left: 10),
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(5), border: Border.all(width: 1, color: Colors.grey)),
                        alignment: Alignment.center,
                        padding: const EdgeInsets.symmetric(vertical: 3, horizontal: 10),
                        child: _buildTF('平台创建的应用AppId', (value) {
                          _appid = value;
                        }, defaultValue: _appid),
                        width: 150,
                        height: 30,
                      )
                    ],
                  ),
                  const SizedBox(
                    width: 50,
                  ),
                  Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(
                        'Appkey:',
                        style: leftStyle,
                      ),
                      Container(
                        margin: const EdgeInsets.only(left: 10),
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(5), border: Border.all(width: 1, color: Colors.grey)),
                        alignment: Alignment.center,
                        padding: const EdgeInsets.symmetric(vertical: 3, horizontal: 10),
                        child: _buildTF('平台创建的应用Appkey', (value) {
                          _appkey = value;
                        }, defaultValue: _appkey),
                        width: 380,
                        height: 30,
                      )
                    ],
                  ),
                ],
              ),
            ),
            Container(
                margin: const EdgeInsets.symmetric(vertical: 10),
                height: 50,
                child: Row(
                  // mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Text(
                          'Version:',
                          style: leftStyle,
                        ),
                        Container(
                          margin: const EdgeInsets.only(left: 10),
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(5), border: Border.all(width: 1, color: Colors.grey)),
                          alignment: Alignment.center,
                          padding: const EdgeInsets.symmetric(vertical: 3, horizontal: 10),
                          child: _buildTF('版本号', (value) {
                            _version = value;
                          }, defaultValue: _version),
                          width: 150,
                          height: 30,
                        )
                      ],
                    ),
                    const SizedBox(
                      width: 50,
                    ),
                    Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Text(
                          'BundleId:',
                          style: leftStyle,
                        ),
                        Container(
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(5), border: Border.all(width: 1, color: Colors.grey)),
                          alignment: Alignment.center,
                          margin: const EdgeInsets.only(left: 10),
                          padding: const EdgeInsets.symmetric(vertical: 3, horizontal: 10),
                          child: _buildTF('包名', (value) {
                            _bundleid = value;
                          }, defaultValue: _bundleid),
                          width: 250,
                          height: 30,
                        )
                      ],
                    )
                  ],
                )),
            _buildItem('工具路径:', _toolPath, () async {
              LWUnitls.chooseFile((path) {
                setState(() {
                  _toolPath = path;
                });
              }, isDirectory: true);
            }),
            _buildItem(_platformValue == "IOS" ? "dSYM文件路径：" : 'symbols文件路径:', _symbolsPath, () async {
              LWUnitls.chooseFile((path) {
                setState(() {
                  _symbolsPath = path;
                });
              });
            }),
            if (_platformValue == 'Android')
              _buildItem('mapping文件路径:', _mappingPath, () async {
                LWUnitls.chooseFile((path) {
                  setState(() {
                    _mappingPath = path;
                  });
                });
              }),
            // Text(
            //     'java -jar buglyqq-upload-symbol.jar -appid ${_appid} -appkey ${_appkey} -bundleid ${_bundleid} -version ${_version} -platform ${_platformValue} -inputSymbol ${_symbolsPath} -inputMapping ${_mappingPath}'),
            GestureDetector(
              child: Container(
                padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 100),
                margin: const EdgeInsets.symmetric(horizontal: 20),
                decoration: BoxDecoration(
                    color: Colors.blue,
                    borderRadius: BorderRadius.circular(5),
                    border: Border.all(width: 1, color: Colors.grey)),
                child: Text(
                  _uploading ? '上传中...' : '开始上传',
                  style: leftStyle,
                ),
              ),
              onTap: () async {
                if (_uploading) return;
                setState(() {
                  _uploading = true;
                });
                logs.clear();
                String commands =
                    'java -jar buglyqq-upload-symbol.jar -appid ${_appid} -appkey ${_appkey} -bundleid ${_bundleid} -version ${_version} -platform ${_platformValue} -inputSymbol ${_symbolsPath} -inputMapping ${_mappingPath}';
                LWUnitls.changeCurrentPath(_toolPath);
                LWUnitls.execute(commands, (data) {
                  setState(() {
                    _uploading = false;
                    logs.add(data);
                  });
                });
                // // 要执行的 shell 命令
                // // String commands = 'ls'; // 启动进程并获取进程对象
                // // Process process = await Process.start(commands, []);
                // Process process = await Process.start('/bin/bash', ['-c', commands]);
                // // 使用流监听标准输出
                // process.stdout.transform(utf8.decoder).listen((String data) {
                //   setState(() {
                //     _uploading = false;
                //     logs.add(data);
                //   });
                //   // 在这里可以更新 UI，显示进度日志
                // });
                //
                // // 使用流监听标准错误
                // process.stderr.transform(utf8.decoder).listen((String data) {
                //   setState(() {
                //     _uploading = false;
                //     logs.add(data);
                //   });
                //   // 在这里可以更新 UI，显示错误日志
                // });
                //
                // // 等待进程执行完成
                // int exitCode = await process.exitCode;
                // // setState(() {
                // //   logs.add(exitCode.toString());
                // // });
              },
            ),
            Expanded(
                child: Container(
              margin: const EdgeInsets.only(top: 20),
              padding: const EdgeInsets.symmetric(horizontal: 10),
              decoration: BoxDecoration(color: Colors.grey.withOpacity(0.3)),
              child: ListView.builder(
                itemBuilder: (context, index) {
                  return Text(
                    logs[index],
                    style: const TextStyle(
                      fontSize: 12,
                    ),
                    maxLines: 100,
                  );
                },
                itemCount: logs.length,
              ),
            ))
          ],
        ),
      ),
    );
  }

  _buildItem(String title, String path, Function callback) {
    return Container(
      alignment: Alignment.centerLeft,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Text(
            title,
            style: leftStyle,
          ),
          Expanded(
              child: Container(
            alignment: Alignment.centerLeft,
            margin: const EdgeInsets.symmetric(horizontal: 20),
            padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 3),
            decoration:
                BoxDecoration(borderRadius: BorderRadius.circular(5), border: Border.all(width: 1, color: Colors.grey)),
            child: Text(
              path,
              maxLines: 2,
              style: const TextStyle(fontSize: 14),
            ),
          )),
          GestureDetector(
            child: Container(
              alignment: Alignment.center,
              height: 50,
              width: 50,
              child: Image.asset(
                'assets/images/file_select_icon.png',
                width: 30,
                height: 30,
              ),
            ),
            onTap: () {
              callback.call();
            },
          ),
        ],
      ),
    );
  }

  _buildTF(String? hitText, Function onChanged, {String defaultValue = ''}) {
    TextEditingController editingController = TextEditingController(text: defaultValue);
    return TextField(
      controller: editingController,
      decoration: InputDecoration(
          isCollapsed: true, border: InputBorder.none, hintText: hitText, hintStyle: const TextStyle(fontSize: 10)),
      onChanged: (value) {
        setState(() {
          if (value.contains(' ')) {
            value = value.replaceAll(' ', '');
          }
          onChanged(value);
        });
      },
    );
  }
}
